<template>
  <div class="topo-background" :style="{ height: availableHeight + 'px'}">
    <div id="visualization" class="network" style="height: 100%;" />
  </div>
</template>

<script>

import vis from 'vis'
import 'vis/dist/vis.min.css'
import resize from '@neu/biz-core/mixins/resize'
import { getTopo } from '@neu/cmdb-ui/api/instance'

export default {
  name: 'VisNetWork',
  mixins: [resize],
  props: {
    instanceId: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      network: null,
      nodes: [],
      edges: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.dataReload()
    })
  },
  methods: {
    initNetwork() {
      const that = this
      // create an array with nodes
      var nodes = new vis.DataSet(this.nodes)

      // create an array with edges
      var edges = new vis.DataSet(this.edges)

      // create a network
      var container = document.querySelector('#visualization')

      // provide the data in the vis format
      var data = {
        nodes: nodes,
        edges: edges
      }
      var options = {
        physics: false
      }

      // initialize your network!
      this.network = new vis.Network(container, data, options)
      this.network.on('click', function(params) {
        const code = this.getNodeAt(params.pointer.DOM)
        const node = that.nodes.find(it => it.id === code)
        if (node) {
          that.routeTo(node._id)
        }
      })
    },
    dataReload() {
      getTopo(this.instanceId).then(response => {
        const nodes = response.data.nodes
        nodes.forEach(n => {
          if (n.icon) {
            n.image = n.icon
            n.shape = 'image'
          }
        })
        this.nodes = nodes
        var edges = response.data.edges
        edges.forEach(e => {
          e.color = { color: 'rgba(30,30,30,0.2)', highlight: 'blue' }
        })
        this.edges = edges

        this.initNetwork()
      })
    },
    getOtherContentHeight() {
      const baseInfoSel = document.querySelector('.instance-edit-container .base-info')
      const baseInfoHeight = baseInfoSel ? baseInfoSel.offsetHeight : 0

      const elTabsHeaderSel = document.querySelector('.instance-edit-container .el-tabs__header')
      const elTabsHeaderHeight = elTabsHeaderSel ? elTabsHeaderSel.offsetHeight + 15 : 0
      return baseInfoHeight + elTabsHeaderHeight + 16 + 5
    },
    routeTo(instanceId) {
      this.$router.push({ name: 'cmdb_instances_detail', params: { id: instanceId }})
    }
  }
}
</script>

<style scoped>
  .topo-background {
    background-image: linear-gradient(#eef1f5 1px,transparent 0),linear-gradient(90deg,#eef1f5 1px,transparent 0);
    background-size: 10px 10px;
  }
</style>

